package com.kylingroup.Desktop.Plugin.FileUploader.Cell;

import com.kylingroup.Desktop.Plugin.FileUploader.Bean.FileTreeItem;
import com.kylingroup.Desktop.Plugin.FileUploader.FileuploaderController;
import java.awt.Desktop;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.image.Image;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javax.swing.SwingUtilities;

public class FileTreeCell extends TreeCell<FileTreeItem>{
    private ContextMenu popupMenu=null;
    
    public FileTreeCell(){
        popupMenu=new ContextMenu();
        initPopupMenu();
    }
    
    private void initPopupMenu(){
        MenuItem itemPreview=new MenuItem("view");
        MenuItem itemInfo=new MenuItem("info");
        popupMenu.getItems().addAll(itemPreview,itemInfo);
        
        itemPreview.setOnAction(new EventHandler(){
            @Override
            public void handle(Event event) {
                if(Desktop.isDesktopSupported()){
                    FileTreeItem item=FileTreeCell.this.getTreeItem().getValue();
                    String filePath=item.getFile().getAbsolutePath();
                    preview(filePath);
                }else{
                    alert();
                }
            }
        });
        
        itemInfo.setOnAction(new EventHandler(){
            @Override
            public void handle(Event event) {
                FileTreeItem item=FileTreeCell.this.getTreeItem().getValue();
                setFileInfos(item);
            }
        });
    }
    
    private void preview(String path){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                Desktop desktop=Desktop.getDesktop();
                            
                try{ 
                    desktop.open(new File(path));
                }catch (Exception e){
                    e.printStackTrace();  
                }
            }
        });
    }
    
    private void alert(){
        Alert alert=new Alert(Alert.AlertType.WARNING, "");
        alert.initModality(Modality.APPLICATION_MODAL);
        alert.initOwner(null);
        alert.getDialogPane().setContentText(Alert.AlertType.WARNING+" text.");
        alert.getDialogPane().setHeaderText(null);
        alert.showAndWait().filter(response -> response==ButtonType.OK).ifPresent(response -> System.out.println("The alert was approved"));
    }
    
    private void setFileInfos(FileTreeItem item){
        HashMap<String,Node> infoNodes=item.getFileInfoNodes();
        String name=item.getFile().getName();
        String size=String.valueOf(item.getFile().length());
        String path=item.getFile().getAbsolutePath();
        
        VBox infobox=(VBox)infoNodes.get("infobox");
        infobox.setVisible(true);
        
        Label filename=(Label)infoNodes.get("filename");
        filename.setText(name);
                
        Label filetype=(Label)infoNodes.get("filetype");
        filetype.setText(name.substring(name.lastIndexOf(".")+1,name.length()));
                
        Label filesize=(Label)infoNodes.get("filesize");
        filesize.setText(size);
                
        Label filepath=(Label)infoNodes.get("filepath");
        filepath.setText(path);
    }
    
    private void bindActions(FileTreeItem item){
        Label source=item.getGraphic();
        
        source.setOnMouseClicked(new EventHandler<MouseEvent>(){
            @Override
            public void handle(MouseEvent event){
                if(event.getButton().PRIMARY==event.getButton()){
                    setFileInfos(item);
                }
            }
        });
        
        source.setOnDragDetected(new EventHandler<MouseEvent>(){
            @Override
            public void handle(MouseEvent event){
                Dragboard db=null;
                db=source.startDragAndDrop(TransferMode.ANY);
               
                Image img=item.getIcon();
                double offsetx=img.getWidth()/2;
                double offsety=img.getHeight()/2;
                db.setDragView(img,offsetx,offsety);
                ClipboardContent content=new ClipboardContent();
                List<File> files=new ArrayList<File>();
                files.add(item.getFile());
                content.putFiles(files);
                db.setContent(content);
                event.consume();
            }
        });
        
        source.setOnDragDone(new EventHandler<DragEvent>(){
            @Override
            public void handle(DragEvent event){
                event.getDragboard().setDragView(null);
                if(FileuploaderController.delemode) {
                    TreeItem<FileTreeItem> parent=FileTreeCell.this.getTreeItem().getParent();
                    parent.getChildren().remove(FileTreeCell.this.getTreeItem());
                    
                }else{
                    
                }
            }
        });
    }

    @Override
    public void updateItem(FileTreeItem item,boolean empty){
        super.updateItem(item, empty);
        if(empty){
            this.setText(null);
            this.setGraphic(null);
        }else{
            item=this.getTreeItem().getValue();
            
            if(!getTreeItem().getValue().getFile().isDirectory()){
                setContextMenu(popupMenu);
                bindActions(item);
            }else{
                
            }
            setGraphic(item.getGraphic());
        }
    }
}

